<template>
  <AdminPage
    title="商家管理"
    :filters="filters"
    :pagination-enabled="true"
    v-model:page="page"
    :total="total"
    :page-size="pageSize"
  >
    <!-- 筛选栏 -->
    <template #filters>
      <el-form-item label="店铺编号" class="filter-item">
        <el-input v-model="filters.storeId" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="店铺名称" class="filter-item">
        <el-input v-model="filters.storeName" placeholder="请输入" clearable size="small" />
      </el-form-item>
     
      <el-form-item label="状态" class="filter-item">
        <el-select v-model="filters.status" placeholder="请选择" clearable size="small">
          <el-option label="正常" :value="1" />
          <el-option label="关闭" :value="2" />
          <el-option label="冻结" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="入驻时间" class="filter-item">
        <div class="date-picker-container">
          <el-date-picker
            v-model="filters.createTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="small"
            width="60" 
          />
        </div>
      </el-form-item>
     
      <el-form-item class="filter-item">
        <el-button type="primary" :icon="Search" @click="handleSearch" size="small">搜索</el-button>
        <el-button @click="handleReset" size="small">重置</el-button>
      </el-form-item>
    </template>

    <!-- 表格 -->
    <template #table>
      <el-table :data="pageData" :loading="loading" border stripe header-cell-class-name="table-header" class="list-table">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="id" label="店铺编号" min-width="100" />
        <el-table-column prop="name" label="店铺名称" min-width="160" />
        <el-table-column label="Logo" min-width="100">
          <template #default="{ row }">
            <div class="logo-container">
              <el-avatar :size="28" :src="row.logo" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="creater" label="负责人" min-width="120" />
        <el-table-column prop="description" label="店铺描述" min-width="140" />
        <el-table-column prop="createTime" label="入驻时间" min-width="180" />
        <el-table-column prop="detail" label="店铺详细地址" min-width="100"/>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="Number(row.status)===1" type="success">正常</el-tag>
            <el-tag v-else-if="Number(row.status)===2" type="info">关闭</el-tag>
            <el-tag v-else type="warning">冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button 
              v-if="Number(row.status)!==1" 
              type="success" 
              size="small"
              @click="handleEnableStore(row.id)"
            >
              解禁
            </el-button>
            <el-button 
              v-else-if="Number(row.status)!==2" 
              type="danger" 
              size="small"
              @click="handleDisableStore(row.id)"
            >
              禁用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #pagination></template>
  </AdminPage>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import {  getMerchantByName,enableMerchantService, disableMerchantService } from '../../api/admin'
import AdminPage from '../../components/admin/AdminPage.vue'

type Store = {
  id: number
  name: string
  logo:string
  description:string
  province:string
  city:string
  district:string
  detail:string
  status: number
  creater: string
  createTime: string
  updateTime:string
}

const filters = reactive({
  storeId: '',
  storeName: '',
  province: '',
  city: '',
  createTime: [] as string[],
  status: undefined as number | undefined
})

const loading = ref(false)
const allData = ref<Store[]>([])

const page = ref(1)
const pageSize = ref(8)
const total = ref(0)

const fetchStores = async () => {
  loading.value = true
  try {
    const res: any = await getMerchantByName(page.value, pageSize.value,filters.storeName)
    const payload = res?.data ?? res
    const records = payload?.records ?? payload?.list ?? payload?.items ?? ([] as Store[])
    allData.value = records as Store[]
    total.value = Number(payload?.total ?? records.length)
  } catch (e) {
    // ignore
  } finally {
    loading.value = false
  }
}

const filteredData = computed(() => {
  return allData.value.filter(row => {
    const matchId = !filters.storeId || String(row.id).includes(filters.storeId)
    const matchName = !filters.storeName || row.name.includes(filters.storeName)
    const matchProvince = !filters.province || row.province === filters.province
    const matchCity = !filters.city || row.city === filters.city
    const matchStatus = filters.status === undefined || Number(row.status) === Number(filters.status)
    
    // 入驻时间范围筛选
    let matchTime = true
    if (filters.createTime && filters.createTime.length === 2) {
      const createTime = new Date(row.createTime).getTime()
      const startTime = new Date(filters.createTime[0]).getTime()
      const endTime = new Date(filters.createTime[1]).getTime()
      matchTime = createTime >= startTime && createTime <= endTime
    }
    
    return matchId && matchName && matchProvince && matchCity && matchStatus && matchTime
  })
})

const pageData = computed(() => {
  // 由服务端分页，表格直接展示当前页数据
  return filteredData.value
})

const handleSearch = () => { page.value = 1; fetchStores() }
const handleReset = () => {
  filters.storeId = ''
  filters.storeName = ''
  filters.province = ''
  filters.city = ''
  filters.createTime = []
  filters.status = undefined
  page.value = 1
  fetchStores()
}

const handleEnableStore = async (storeId: number) => {
  try {
    console.log('解禁商家，商家ID:', storeId)     
    await enableMerchantService(storeId)
    ElMessage.success('解禁商家成功')
    fetchStores()
  } catch (error) {
    console.error('解禁商家失败:', error)
    ElMessage.error('解禁商家失败')
  }
}

const handleDisableStore = async (storeId: number) => {
  try {
    console.log('禁用商家，商家ID:', storeId)
    await disableMerchantService(storeId)
    ElMessage.success('禁用商家成功')
    fetchStores()
  } catch (error) {
    console.error('禁用商家失败:', error)
    ElMessage.error('禁用商家失败')
  }
}

// 分页事件由 AdminPage 统一触发（v-model:page）

onMounted(fetchStores)
watch([page, pageSize], fetchStores)
</script>


